package com.hxwm.hwdbtool.util;

import org.mozilla.universalchardet.UniversalDetector;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @program: hwdbtool
 * @ClassName FileCharacterSet
 * @description:
 * @author: hxwm
 * @create: 2024-06-02 21:16
 * @Version 1.0
 **/
public class HwFileUtil {

    public static Charset characterSetMapper(String characterSet){
        Charset exportCharacterSet = StandardCharsets.UTF_8;
        switch (characterSet){
            case "UTF-8" :
                exportCharacterSet = StandardCharsets.UTF_8;
                break;
            case "UTF-16" :
                exportCharacterSet = StandardCharsets.UTF_16;
                break;
            case "ISO-8859-1" :
                exportCharacterSet = StandardCharsets.ISO_8859_1;
                break;
            case "US-ASCII" :
                exportCharacterSet = StandardCharsets.US_ASCII;
                break;
            case "GBK" :
                exportCharacterSet = Charset.forName("GBK");
                break;
            case "GB18030":
                exportCharacterSet = Charset.forName("GB18030");
                break;
            default:
                exportCharacterSet = Charset.forName(characterSet);
                break;
        }
        return exportCharacterSet;
    }

    public static String detectFileEncoding(String filePath) {
        byte[] buf = new byte[4096];
        UniversalDetector detector = new UniversalDetector(null);
        File file = new File(filePath);
        try (FileInputStream fis = new FileInputStream(file)) {
            int nread;
            while ((nread = fis.read(buf)) > 0 && !detector.isDone()) {
                detector.handleData(buf, 0, nread);
            }
            detector.dataEnd();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return detector.getDetectedCharset();
    }

    /**
     * 获取指定文件的行数
     * @param path
     * @return
     */
    public static int countLines(String path){
        try(BufferedReader reader = new BufferedReader(new FileReader(path))){
            int line = 0;
            while(reader.readLine()!=null){
                line ++;
            }
            return line;
        }catch(IOException e){
            e.printStackTrace();
            return -1;
        }
    }
}